﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebNext.UI.Utils;
using WebNext.UI.Properties;
using WebNext.UI.Utils.Validators;

namespace WebNext.UI.Models.Contact
{
	public class ContactViewModel : MainViewModel
	{
		public const int MaxSenderLength = 50;
		public const int MaxMessageLength = 5000;

		public string Sender
		{
			get;
			set;
		}

		public string Email
		{
			get;
			set;
		}

		public string MessageContent
		{
			get;
			set;
		}

		public string CaptchaKey
		{
			get;
			set;
		}

		public string CaptchaValue
		{
			get;
			set;
		}

		public bool IsCaptchaValid
		{
			get;
			private set;
		}

		public bool IsSenderValid
		{
			get;
			private set;
		}

		public bool IsMessageContentValid
		{
			get;
			private set;
		}

		public ContactViewModel(bool isLogged) : base(isLogged)
		{
			this.IsSenderValid = true;
			this.IsMessageContentValid = true;
			this.IsCaptchaValid = true;

			this.ViewType = MainViewType.Contact;

			this.PageTitle = string.Format(Resources.TitleFormat, RuntimeSettings.SitePrefix, Resources.Contact);
			this.PageName = Resources.Contact;
			this.PageDescription = Resources.ContactAuthor;
		}

		public ValidationResult Validate()
		{
			ValidationResult result = new ValidationResult();

			if (string.IsNullOrEmpty(this.Sender))
			{
				result.AddError(Resources.SenderCannotBeEmpty);
				this.IsSenderValid = false;
			}
			else if(this.Sender.Length > MaxSenderLength)
			{
				result.AddError(Resources.SenderTooLong, MaxSenderLength);
				this.IsSenderValid = false;
			}

			if(string.IsNullOrEmpty(this.MessageContent))
			{
				result.AddError(Resources.MessageCannotBeEmpty);
				this.IsMessageContentValid = false;
			}
			else if (this.MessageContent.Length > MaxMessageLength)
			{
				result.AddError(Resources.MessageTooLong, MaxMessageLength);
				this.IsMessageContentValid = false;
			}

			IValidator captchaValidator = new CaptchaValidator(this.CaptchaKey, this.CaptchaValue);
			ValidationResult captchaValidationResult = captchaValidator.Validate();
			if (!captchaValidationResult.IsValid)
			{
				result.Merge(captchaValidationResult);
				this.IsCaptchaValid = false;
			}

			return result;
		}
	}
}